package com.eagle.gennewdata;
import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.http.*;

import com.eagle.gennewdata.model.NewDaoFactory;
import com.eagle.gennewdata.model.NewImgItem;
import com.eagle.gennewdata.model.WebSetting;
import com.eagle.gennewdata.untl.GlobalsFun;

@SuppressWarnings("serial")
public class ListImgDataServlet extends HttpServlet {
	public static boolean s_bIsRunGen = false;
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		resp.setContentType("application/octet-stream;charset=utf-8");
		resp.setHeader("Pragma", "No-cache");
		resp.setHeader("Cache-Control", "no-cache");
		resp.setDateHeader("Expires", 0);
		int nStart = 0;
		int nCount = WebSetting.nDefPageCount;
		int nPage = 1;
		
		boolean bRefrash = false;
		if (req.getParameter("refrash") != null)
			bRefrash = true;
		
		String strCategory = WebSetting.strDefaultCategory;
		
		if (req.getParameter("page") != null) 
		{
			nPage = Integer.valueOf(req.getParameter("page").toString());
			nStart = (nPage - 1) * nCount;
			nCount = nStart + nCount;
		}
	
		Date dateNow = new Date();

		if (nPage < 10 && nPage >0 && bRefrash == false ) {
			if ((dateNow.getTime() - WebSetting.arrListImgCheckSum[nPage -1]) < WebSetting.timeGetNewGapTime && WebSetting.arrListImgString[nPage - 1] != null) 
			{
				GlobalsFun.WriteBuffer(resp, WebSetting.arrListImgString[nPage - 1].getBytes("UTF-8"));
				return;
			}
		}
		
		
		List<NewImgItem> listNews = NewDaoFactory.queryNewImgsByTitle(nStart, nCount);
		String strlogo = "";
		String strReturnText = "";
		if (listNews != null) {
			
			for (NewImgItem item : listNews) {
				strReturnText += String.format(WebSetting.strImgItemFormat, 
						item.getId(),
						item.getLink(),
						item.getTitle()
						);
			}
			String strSaveString = String.format(WebSetting.strNewXmlFormat, 
					strCategory,
					strlogo,
					strReturnText); 
			if (nPage < 10 && nPage > 0) {
				WebSetting.arrListImgString[nPage - 1] = strSaveString;
				WebSetting.arrListImgCheckSum[nPage - 1] = dateNow.getTime();
			}
			GlobalsFun.WriteBuffer(resp, strSaveString.getBytes("UTF-8"));
		}
	}
}
